<?php

declare(strict_types=1);

namespace app\middleware;

use think\facade\Db;

class PermissionCheck
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $no_nedd_auth_url = [
            'api/auth/getInfo',
            'api/auth/getRouters',
            'api/sysUser/profile',
            'api/sysUser/updateProfile',
            'api/sysUser/updatePwd',
            'api/dictType/getData'
        ];
        $request_route_rule = $request->rule()->getRule();
        $perm = str_replace('/', ':', $request_route_rule);

        $user_id = $request->create_by;
        //超级管理员直接跳过
        if ($user_id === 100 || in_array($request_route_rule, $no_nedd_auth_url)) {
            return $next($request);
        }
        $roles_id = Db::table('sys_user_role')->where('user_id', $user_id)->column('role_id');
        //获取角色菜单
        $role_menus_id = DB::table('sys_role_menu')->whereIn('role_id', $roles_id)->column('menu_id');
        //获取菜单
        $perms_menus = Db::table('sys_menu')->whereIn('id', $role_menus_id)->where('menu_type', 'F')->column('perms');
        if (!in_array($perm, $perms_menus)) {
            return error('无权限');
        }

        return $next($request);
    }
}
